package com.gy.api.mobile.app;

import com.gy.api.base.ApiIndex;
import com.gy.api.pc.region.domain.vo.Region;
import com.gy.api.pc.region.service.IRegionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

@RestController
@RequestMapping("/region")
@Api( tags = ApiIndex.RegionController)
@Slf4j
public class RegionController {

    @Autowired
    private IRegionService regionService;

    @GetMapping("/{id}")
    @ApiOperation("根据ID对应下面的获取子数据")
    public List<Region> getChildrenByParentId(@PathVariable("id") Long parentId) {
        return regionService.getChildrenByParentId(parentId);
    }

    @GetMapping("/index")
    @ApiOperation("重庆区域首页下拉框")
    public List<Region> Index() {
        Long parentId = 4287L;
        return regionService.getChildrenByParentId(parentId);
    }

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("File is empty");
        }

        try {
            // 保存文件到临时文件，并确保使用 File.separator
            String tempDir = System.getProperty("java.io.tmpdir");
            String filePath = tempDir + File.separator + file.getOriginalFilename();
            File dest = new File(filePath);
            file.transferTo(dest);

            // 调用服务层方法来处理 JSON 数据
            regionService.importRegionsFromFile(dest);

            // 删除临时文件
            dest.delete();

            return ResponseEntity.ok("File uploaded and data imported successfully");
        } catch (Exception e) {
//            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file: " + e.getMessage());
        }
    }

}
